﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RMS.Utils.BackgroundTasks;
using RMS.Utils.EventAggregators;
using RMS.Utils.RulesManager;
using RMS.DataAccess.Entities;
using RMS.Utils.Dicom;
using RMS.Utils.Histogram;

namespace RMS.Web.Shell.Services
{
    public class DicomBootstraperTask : IBackgroundTask
    {
        private IEventAggregator _eventAggregator;
        private IHistogram _histogram;
        private IDicomBase _dicomBase;
        private IRulesManager _rulesManager;

        public DicomBootstraperTask(IEventAggregator eventAggregator, IRulesManager rulesManager
            , IHistogram histogram, IDicomBase dicomBase)
        {
            this._eventAggregator = eventAggregator;
            this._histogram = histogram;
            this._dicomBase = dicomBase;
            this._rulesManager = rulesManager;
        }


        public void Start()
        {
            _eventAggregator.GetEvent<EntityAction>().Subscribe(OnAction);
        }
        private void OnAction(EntityActionEventArgs e)
        {
            var dlgt = _rulesManager.Find(e.Entity.GetType(), e.State);
          string x = e.Entity.GetType().ToString();
            if (e.State == EntityState.Inserting && e.Entity.GetType()== typeof(RadiologyImage))
            {
                var entity = (RadiologyImage)e.Entity;
                _dicomBase.FilePath = entity.ImagePath;
                _dicomBase.SaveImage(entity.ImagePath + ".Jpg");
                _dicomBase.SaveDicomAsXml(entity.ImagePath+ ".xml");
                entity.Histogram = _histogram.GetHistogram(entity.ImagePath + ".Jpg");
                dlgt.DynamicInvoke(e.Entity);
            }
        }
        public void Stop()
        {
            _eventAggregator.GetEvent<EntityAction>().Unsubscribe(OnAction);
        }
    }
}